package jp.ac.aiit.yc.softarch.hbcp.service.common;

import java.util.ArrayList;
import java.util.List;

import flex.messaging.MessageBroker;
import flex.messaging.messages.AsyncMessage;
import flex.messaging.util.UUIDUtils;

import jp.ac.aiit.yc.softarch.hbcp.model.common.User;

public class LoginService {
	private static List<User> users = new ArrayList<User>();
	static {
		users.add(new User("user1", "user1"));
		users.add(new User("user2", "user2"));
		users.add(new User("user3", "user3"));
	}
	public boolean canLogin(User user){
		System.out.println("canLogin");
		System.out.println("user.name=" + user.name);
		System.out.println("user.password=" + user.password);
		if( isExists(user)) {
			MessageBroker messageBroker = MessageBroker.getMessageBroker(null);
			String clientID = UUIDUtils.createUUID();

			AsyncMessage msg = new AsyncMessage();
			msg.setDestination("hbcp");
			msg.setClientId(clientID);
			msg.setMessageId(UUIDUtils.createUUID());
			msg.setTimestamp(System.currentTimeMillis());
			msg.setHeader("operation", "login");
			msg.setBody(user);
			messageBroker.routeMessageToService(msg, null);
			System.out.println(user.name + " can login");
			return true;
		} else {
			return false;
		}
	}

	protected boolean isExists(User user) {
		for (User u : users) {
			if (u.name.equals(user.name) && u.password.equals(user.password)) {
				System.out.println(user.name + " is exists");
				return true;
			}
		}
		System.out.println(user.name + " is not exists");
		return false;
	}
}
